<template>
  <view class="shop-detail-container">
    <!-- 顶部搜索栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input type="text" :placeholder="'请输入商品名称'" />
      </view>
    </view>
    
    <!-- 店铺信息 -->
    <view class="shop-info">
      <image :src="shop.imgUrl" mode="aspectFill"></image>
      <view class="shop-data">
        <text class="shop-name">{{shop.name}}</text>
        <view class="shop-stats">
          <text>月售：{{shop.sales}}</text>
          <text>起送：{{shop.expressLimit}}</text>
          <text>基础运费：{{shop.expressPrice}}</text>
        </view>
        <text class="shop-slogan" :style="{color: '#ff6b6b'}">{{shop.slogan}}</text>
      </view>
    </view>
    
    <!-- 导航 -->
    <view class="category-nav">
      <view class="category-left">
        <text class="category-item" :class="{ active: currentCategory === 'all' }" @click="changeCategory('all')">全部商品</text>
        <text class="category-item" :class="{ active: currentCategory === 'seckill' }" @click="changeCategory('seckill')">秒杀</text>
        <text class="category-item" :class="{ active: currentCategory === 'fruit' }" @click="changeCategory('fruit')">新鲜水果</text>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <view class="product-list">
      <view class="product-item" v-for="(product, index) in products" :key="index">
        <image :src="product.imgUrl" mode="aspectFill"></image>
        <view class="product-info">
          <text class="product-name">{{product.name}}</text>
          <text class="product-sales">月售 {{product.sales}} 件</text>
          <view class="product-price">
            <text class="current-price">¥{{product.price}}</text>
            <text class="old-price">¥{{product.oldPrice}}</text>
            <view class="quantity-control">
              <text class="minus" v-if="getProductCount(product._id) > 0" @click="decreaseCart(product)">-</text>
              <text class="count" v-if="getProductCount(product._id) > 0">{{getProductCount(product._id)}}</text>
              <text class="plus" @click="addToCart(product)">+</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部购物车 -->
    <view class="cart-bar" v-if="getTotalCount > 0">
      <view class="cart-icon" @click="toggleCartPopup">
        <image src="/static/icon/购物车.png" mode="aspectFit" style="width: 60rpx; height: 60rpx;"></image>
        <view class="cart-count">{{getTotalCount}}</view>
      </view>
      <view class="cart-price">
        <text>总计: ¥ {{getTotalPrice.toFixed(2)}}</text>
      </view>
      <view class="checkout-btn" @click="goToOrderConfirm">
        去结算
      </view>
    </view>
    
    <!-- 购物车弹窗 -->
    <view class="cart-popup" v-if="showCartPopup">
      <view class="cart-popup-mask" @click="toggleCartPopup"></view>
      <view class="cart-popup-content">
        <view class="cart-popup-header">
          <text class="cart-popup-title">购物车</text>
          <text class="cart-popup-clear" @click="clearCart">清空购物车</text>
        </view>
        
        <scroll-view scroll-y class="cart-popup-list">
          <view class="cart-popup-item" v-for="(product, index) in cartProductsList" :key="product.uniqueId">
            <view class="cart-popup-item-info">
              <image :src="product.imgUrl" mode="aspectFill"></image>
              <view class="cart-popup-item-detail">
                <text class="cart-popup-item-name">{{product.name}} {{product.weight || ''}}</text>
                <view class="cart-popup-item-price">
                  <text class="price">¥{{product.price}}</text>
                  <text class="old-price" v-if="product.oldPrice">¥{{product.oldPrice}}</text>
                </view>
              </view>
            </view>
            <view class="quantity-control">
              <text class="minus" @click="decreaseCart(product)">-</text>
              <text class="count">{{cartProducts[product.uniqueId]}}</text>
              <text class="plus" @click="addToCart(product)">+</text>
            </view>
          </view>
        </scroll-view>
        
        <view class="cart-popup-footer">
          <view class="cart-popup-total">
            <text>合计: ¥ {{getTotalPrice.toFixed(2)}}</text>
          </view>
          <view class="cart-popup-checkout" @click="goToOrderConfirm">
            去结算({{getTotalCount}})
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopId: '',
      shopName: '',
      shop: {},
      products: [],
      currentCategory: 'all',
      cartProducts: {},
      showCartPopup: false, // 控制购物车弹窗显示
      productsPrefix: '' // 用于区分不同超市的商品数据前缀
    }
  },
  computed: {
    getTotalCount() {
      let count = 0;
      for (const id in this.cartProducts) {
        // 只计算当前超市的商品
        if (id.startsWith(`${this.shopId}_`)) {
          count += this.cartProducts[id];
        }
      }
      return count;
    },
    getTotalPrice() {
      let total = 0;
      for (const id in this.cartProducts) {
        // 只计算当前超市的商品
        if (id.startsWith(`${this.shopId}_`)) {
          const cartProductsInfo = uni.getStorageSync('cartProductsInfo') || '{}';
          const productsInfo = JSON.parse(cartProductsInfo);
          const product = productsInfo[id];
          
          if (product) {
            total += product.price * this.cartProducts[id];
          }
        }
      }
      return total;
    },
    
    // 购物车商品列表
    cartProductsList() {
      const list = [];
      const cartProductsInfo = uni.getStorageSync('cartProductsInfo') || '{}';
      const productsInfo = JSON.parse(cartProductsInfo);
      
      for (const id in this.cartProducts) {
        if (this.cartProducts[id] > 0 && id.startsWith(`${this.shopId}_`)) {
          const product = productsInfo[id];
          if (product) {
            list.push(product);
          }
        }
      }
      return list;
    }
  },
  onLoad(options) {
    console.log('shop-detail onLoad:', options);
    this.shopId = options.id || '';
    this.shopName = decodeURIComponent(options.name || '');
    
    // 获取搜索关键词
    if (options.keyword) {
      this.searchKeyword = decodeURIComponent(options.keyword);
    }
    
    this.fetchShopDetail();
    
    // 从本地存储加载购物车数据
    const cartData = uni.getStorageSync('cartData');
    if (cartData) {
      this.cartProducts = JSON.parse(cartData);
    }
  },
  methods: {
    fetchShopDetail() {
      uni.request({
        url: 'http://localhost:3000/hotList',
        success: (res) => {
          console.log('获取店铺列表成功:', res.data);
          if (res.statusCode === 200) {
            const shop = res.data.find(item => item._id === this.shopId);
            if (shop) {
              this.shop = shop;
              
              // 根据shopId确定使用哪个商品数据集
              if (this.shopId === '2') {
                this.productsPrefix = '-1';
              } else {
                this.productsPrefix = '';
              }
              
              // 获取商品数据
              this.fetchProducts();
            } else {
              // 如果找不到，使用默认数据
              this.shop = {
                name: this.shopName,
                imgUrl: '/static/imgs/near.png',
                sales: 10000,
                expressLimit: 0,
                expressPrice: 5,
                slogan: 'VIP尊享满89元减4元运费券'
              };
              this.productsPrefix = '';
              this.fetchProducts();
            }
          }
        },
        fail: (err) => {
          console.error('获取店铺详情失败:', err);
          // 使用默认数据
          this.shop = {
            name: this.shopName,
            imgUrl: '/static/imgs/near.png',
            sales: 10000,
            expressLimit: 0,
            expressPrice: 5,
            slogan: 'VIP尊享满89元减4元运费券'
          };
          this.productsPrefix = '';
          this.fetchProducts();
        }
      });
    },
    fetchProducts() {
      // 使用带有前缀的URL获取商品数据
      const url = `http://localhost:3000/products-all${this.productsPrefix}`;
      
      uni.request({
        url: url,
        success: (res) => {
          console.log('获取商品数据成功:', res.data);
          if (res.statusCode === 200) {
            this.products = res.data;
          }
        },
        fail: (err) => {
          console.error('获取商品数据失败:', err);
        }
      });
    },
    changeCategory(category) {
      this.currentCategory = category;
      let url = `http://localhost:3000/products-all${this.productsPrefix}`;
      
      if (category === 'all') {
        url = `http://localhost:3000/products-all${this.productsPrefix}`;
      } else if (category === 'seckill') {
        url = `http://localhost:3000/products-seckill${this.productsPrefix}`;
      } else if (category === 'fruit') {
        url = `http://localhost:3000/products-fruit${this.productsPrefix}`;
      }
      
      uni.request({
        url: url,
        success: (res) => {
          console.log(`获取${category}分类商品成功:`, res.data);
          if (res.statusCode === 200) {
            this.products = res.data;
          }
        },
        fail: (err) => {
          console.error(`获取${category}分类商品失败:`, err);
        }
      });
    },
    addToCart(product) {
      // 创建一个包含超市信息的唯一商品ID
      const uniqueProductId = `${this.shopId}_${product._id}`;
      
      if (!this.cartProducts[uniqueProductId]) {
        // 使用Vue.set确保新添加的属性是响应式的
        this.$set(this.cartProducts, uniqueProductId, 0);
      }
      this.cartProducts[uniqueProductId]++;
      
      // 为商品添加shopId和shopName属性
      const productWithShopInfo = {
        ...product,
        shopId: this.shopId,
        shopName: this.shop.name,
        uniqueId: uniqueProductId // 添加唯一标识
      };
      
      // 保存到本地存储
      uni.setStorageSync('cartData', JSON.stringify(this.cartProducts));
      
      // 保存商品信息到本地存储，用于购物车页面显示
      const cartProductsInfo = uni.getStorageSync('cartProductsInfo') || '{}';
      const productsInfo = JSON.parse(cartProductsInfo);
      productsInfo[uniqueProductId] = productWithShopInfo;
      uni.setStorageSync('cartProductsInfo', JSON.stringify(productsInfo));
      
      // 显示提示
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
    },
    decreaseCart(product) {
      // 使用复合键作为唯一标识
      const uniqueProductId = product.uniqueId || `${this.shopId}_${product._id}`;
      
      if (this.cartProducts[uniqueProductId] > 0) {
        this.cartProducts[uniqueProductId]--;
        
        if (this.cartProducts[uniqueProductId] === 0) {
          // 使用Vue.delete确保删除属性时视图会更新
          this.$delete(this.cartProducts, uniqueProductId);
        }
        
        // 保存到本地存储
        uni.setStorageSync('cartData', JSON.stringify(this.cartProducts));
      }
    },
    goToCart() {
      uni.navigateTo({
        url: '/pages/cart/cart'
      });
    },
    
    // 跳转到订单确认页面
    goToOrderConfirm() {
      if (this.getTotalCount === 0) {
        uni.showToast({
          title: '购物车为空',
          icon: 'none'
        });
        return;
      }
      
      // 保存店铺信息到本地存储
      uni.setStorageSync('shopInfo', JSON.stringify(this.shop));
      
      // 只保存当前超市的购物车数据
      const currentShopCart = {};
      const currentShopProducts = {};
      
      // 筛选当前超市的商品
      for (const id in this.cartProducts) {
        if (id.startsWith(`${this.shopId}_`)) {
          currentShopCart[id] = this.cartProducts[id];
          
          // 获取商品信息
          const cartProductsInfo = uni.getStorageSync('cartProductsInfo') || '{}';
          const productsInfo = JSON.parse(cartProductsInfo);
          if (productsInfo[id]) {
            currentShopProducts[id] = productsInfo[id];
          }
        }
      }
      
      // 保存当前超市的购物车数据
      uni.setStorageSync('currentOrderCart', JSON.stringify(currentShopCart));
      uni.setStorageSync('currentOrderProducts', JSON.stringify(currentShopProducts));
      
      // 跳转到订单确认页面
      uni.navigateTo({
        url: '/pages/order/order-confirm'
      });
    },
    
    goBack() {
      uni.navigateBack();
    },
    
    // 切换购物车弹窗显示状态
    toggleCartPopup() {
      this.showCartPopup = !this.showCartPopup;
    },
    
    // 获取商品数量
    getProductCount(productId) {
      const uniqueProductId = `${this.shopId}_${productId}`;
      return this.cartProducts[uniqueProductId] || 0;
    },
    
    // 清空购物车 - 只清空当前超市的商品
    clearCart() {
      uni.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: (res) => {
          if (res.confirm) {
            // 只清空当前超市的商品
            const newCartProducts = {};
            for (const id in this.cartProducts) {
              if (!id.startsWith(`${this.shopId}_`)) {
                newCartProducts[id] = this.cartProducts[id];
              }
            }
            
            this.cartProducts = newCartProducts;
            uni.setStorageSync('cartData', JSON.stringify(this.cartProducts));
            
            // 清空当前超市的商品信息
            const cartProductsInfo = uni.getStorageSync('cartProductsInfo') || '{}';
            const productsInfo = JSON.parse(cartProductsInfo);
            
            for (const id in productsInfo) {
              if (id.startsWith(`${this.shopId}_`)) {
                delete productsInfo[id];
              }
            }
            
            uni.setStorageSync('cartProductsInfo', JSON.stringify(productsInfo));
            this.showCartPopup = false;
            
            uni.showToast({
              title: '购物车已清空',
              icon: 'success'
            });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
.shop-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx; /* 为底部购物车留出空间 */
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  
  .back-btn {
    margin-right: 20rpx;
  }
  
  .search-box {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 30rpx;
    padding: 10rpx 20rpx;
    
    input {
      flex: 1;
      font-size: 26rpx;
      margin-left: 10rpx;
    }
  }
}

.shop-info {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  
  image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
  }
  
  .shop-data {
    flex: 1;
    
    .shop-name {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .shop-stats {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 10rpx;
      
      text {
        font-size: 24rpx;
        color: #666;
        margin-right: 20rpx;
      }
    }
    
    .shop-slogan {
      font-size: 24rpx;
    }
  }
}

.category-nav {
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  
  .category-left {
    display: flex;
    
    .category-item {
      padding: 20rpx 30rpx;
      font-size: 28rpx;
      color: #333;
      position: relative;
      
      &.active {
        color: #0086ff;
        font-weight: bold;
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 40rpx;
          height: 4rpx;
          background-color: #0086ff;
        }
      }
    }
  }
}

.product-list {
  padding: 20rpx;
  
  .product-item {
    display: flex;
    padding: 20rpx;
    background-color: #fff;
    margin-bottom: 20rpx;
    border-radius: 12rpx;
    
    image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }
    
    .product-info {
      flex: 1;
      position: relative;
      
      .product-name {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }
      
      .product-sales {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 20rpx;
      }
      
      .product-price {
        display: flex;
        align-items: center;
        
        .current-price {
          font-size: 32rpx;
          color: #ff6b6b;
          font-weight: bold;
          margin-right: 10rpx;
        }
        
        .old-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
        
        .quantity-control {
          position: absolute;
          right: 0;
          bottom: 0;
          display: flex;
          align-items: center;
          
          .minus, .plus {
            width: 50rpx;
            height: 50rpx;
            line-height: 46rpx;
            text-align: center;
            border-radius: 50%;
            border: 1rpx solid #eee;
            font-size: 28rpx;
          }
          
          .count {
            margin: 0 20rpx;
            font-size: 28rpx;
          }
          
          .plus {
            background-color: #0086ff;
            color: #fff;
            border: none;
          }
        }
      }
    }
  }
}

.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .cart-icon {
    position: relative;
    margin-right: 20rpx;
    
    .cart-count {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      background-color: #ff6b6f;
      color: #fff;
      font-size: 20rpx;
      width: 36rpx;
      height: 36rpx;
      border-radius: 50%;
      text-align: center;
      line-height: 36rpx;
    }
  }
  
  .cart-price {
    flex: 1;
    font-size: 28rpx;
  }
  
  .checkout-btn {
    background-color: #0086ff;
    color: #fff;
    padding: 10rpx 30rpx;
    border-radius: 30rpx;
    font-size: 28rpx;
  }
}

// 购物车弹窗样式
.cart-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  
  .cart-popup-mask {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }
  
  .cart-popup-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    max-height: 70vh;
    display: flex;
    flex-direction: column;
    
    .cart-popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      .cart-popup-title {
        font-size: 32rpx;
        font-weight: bold;
      }
      
      .cart-popup-clear {
        font-size: 26rpx;
        color: #999;
      }
    }
    
    .cart-popup-list {
      flex: 1;
      max-height: 50vh;
      
      .cart-popup-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 30rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        .cart-popup-item-info {
          display: flex;
          align-items: center;
          flex: 1;
          
          image {
            width: 120rpx;
            height: 120rpx;
            border-radius: 8rpx;
            margin-right: 20rpx;
          }
          
          .cart-popup-item-detail {
            flex: 1;
            
            .cart-popup-item-name {
              font-size: 28rpx;
              margin-bottom: 10rpx;
            }
            
            .cart-popup-item-price {
              .price {
                font-size: 30rpx;
                color: #ff6b6b;
                font-weight: bold;
              }
              
              .old-price {
                font-size: 24rpx;
                color: #999;
                text-decoration: line-through;
                margin-left: 10rpx;
              }
            }
          }
        }
        
        .quantity-control {
          display: flex;
          align-items: center;
          
          .minus, .plus {
            width: 50rpx;
            height: 50rpx;
            line-height: 46rpx;
            text-align: center;
            border: 1rpx solid #eee;
            border-radius: 50%;
            font-size: 28rpx;
          }
          
          .minus {
            color: #999;
          }
          
          .plus {
            color: #0086ff;
            border-color: #0086ff;
          }
          
          .count {
            margin: 0 20rpx;
            font-size: 28rpx;
          }
        }
      }
    }
    
    .cart-popup-footer {
      display: flex;
      align-items: center;
      padding: 20rpx 30rpx;
      border-top: 1rpx solid #f5f5f5;
      
      .cart-popup-total {
        flex: 1;
        font-size: 30rpx;
        font-weight: bold;
      }
      
      .cart-popup-checkout {
        background-color: #0086ff;
        color: #fff;
        padding: 15rpx 30rpx;
        border-radius: 30rpx;
        font-size: 28rpx;
      }
    }
  }
}
</style>